package com.xinchao.controller;

import com.xinchao.constant.BusinessConstant;
import com.xinchao.constant.RequestConstant;
import com.xinchao.constant.ResponseConstant;
import com.xinchao.exception.ControllerException;
import com.xinchao.model.User;
import com.xinchao.model.page.PageInfo;
import com.xinchao.model.sys.JsonResponse;
import com.xinchao.model.vo.UserListVO;
import com.xinchao.service.UserService;
import com.xinchao.util.HttpUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用户Controller
 *
 * @author dxy
 * @date 2018/6/21 15:13
 */
@Controller
@RequestMapping("/user")
public class UserController {
	private static Logger logger = LoggerFactory.getLogger(UserController.class);
	/**
	 * 密码正则表达式匹配（与前端一致）
	 */
	private static Pattern PASSWORD_PATTERN = Pattern.compile("^[\\w\\d._]{6,14}$");
	@Autowired
	private UserService userService;

	/**
	 * 跳转至修改密码界面
	 */
	@RequestMapping(value = "/goUpdatePassword")
	public String goUpdatePassword() {
		return "password_update";
	}

	/**
	 * 修改密码
	 */
	@ResponseBody
	@RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
	public Object updatePassword(String originalPassword, String newPassword, String confirmPassword, HttpServletRequest request) {
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		if (StringUtils.isBlank(originalPassword)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "原始密码不能为空");
		}
		String originalPasswordMd5 = DigestUtils.md5Hex(originalPassword);
		if (!originalPasswordMd5.equals(loginUser.getPassword())) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "原始密码不正确");
		}
		if (StringUtils.isBlank(newPassword)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "新密码不能为空");
		}
		if (StringUtils.isBlank(confirmPassword)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "确认密码不能为空");
		}
		//校验密码的长度和是否包含特殊字符及长度，
		Matcher newMatcher = PASSWORD_PATTERN.matcher(newPassword);
		if (!newMatcher.matches()) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "密码长度为6-14位，且不能包含特殊字符");
		}
		//校验密码的长度和是否包含特殊字符及长度，
		Matcher confirmMatcher = PASSWORD_PATTERN.matcher(confirmPassword);
		if (!confirmMatcher.matches()) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "密码长度为6-14位，且不能包含特殊字符");
		}
		if (!newPassword.equals(confirmPassword)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "新密码和确认密码不一致");
		}
		Long userId = loginUser.getUserId();
		//校验密码是否与原始密码相同
		if (DigestUtils.md5Hex(confirmPassword).equals(loginUser.getPassword())) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "新输入密码与原始密码相同，请重新输入");
		}
		try {
			userService.updatePassword(userId, newPassword, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("UserController updatePassword 修改密码失败：" + e.getMessage());
			return new ControllerException("修改密码失败");
		}
		//从session中删除登录用户信息
		request.getSession().removeAttribute(RequestConstant.SESSION_KEY_USER);
		return "";
	}

	/**
	 * 保存用戶
	 */
	@ResponseBody
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public Object saveUser(User user, String roleIds, HttpServletRequest request) {
		String userName = user.getUserName();
		if (StringUtils.isBlank(userName)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "用戶名称不能为空");
		}
		String password = user.getPassword();
		if (StringUtils.isBlank(password)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "密码不能为空");
		}
		//必须选择部门
		if (user.getDepartmentId() == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "请选择部门");
		}
		//姓名
		String realName = user.getRealname();
		if (StringUtils.isBlank(realName)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "姓名不能为空");
		}
		//手机号
		if (StringUtils.isBlank(user.getMobilePhone())) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "手机号不能为空");
		}
		//邮箱
		if (StringUtils.isBlank(user.getEmail())) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "邮箱不能为空");
		}
		//校验密码的长度和是否包含特殊字符及长度，
		Matcher matcher = PASSWORD_PATTERN.matcher(password);
		if (!matcher.matches()) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "密码长度为6-14位，且不能包含特殊字符");
		}
		//验证用户名不能重复
		User oldUser = userService.getUserByUserName(user.getUserName());
		if (oldUser != null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "用户名已存在");
		}
		try {
			//验证姓名不能重复
			User realNameUser = userService.getUserByRealName(realName);
			if (realNameUser != null) {
				return new JsonResponse(ResponseConstant.CODE_FAIL, "姓名已存在");
			}
			//保存用户
			userService.insertUser(user, roleIds, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("UserController saveUser 保存用戶失败：" + e.getMessage());
			return new ControllerException("保存用戶失败");
		}
		return "";
	}

	/**
	 * 修改用户
	 */
	@ResponseBody
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public Object updateUser(User user, String roleIds, HttpServletRequest request) {
		// 参数验证
		String userName = user.getUserName();
		if (StringUtils.isBlank(userName)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "用戶名称不能为空");
		}
		//必须选择部门
		if (user.getDepartmentId() == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "请选择部门");
		}
		//姓名
		String realName = user.getRealname();
		if (StringUtils.isBlank(realName)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "姓名不能为空");
		}
		//手机号
		if (StringUtils.isBlank(user.getMobilePhone())) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "手机号不能为空");
		}
		//邮箱
		if (StringUtils.isBlank(user.getEmail())) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "邮箱不能为空");
		}
		//密码
		String password = user.getPassword();
		if (StringUtils.isNotBlank(password)) {
			//校验密码的长度和是否包含特殊字符及长度，
			Matcher matcher = PASSWORD_PATTERN.matcher(password);
			if (!matcher.matches()) {
				return new JsonResponse(ResponseConstant.CODE_FAIL, "密码长度为6-14位，且不能包含特殊字符");
			}
		}
		//验证用户名不能重复
		User oldUser = userService.getUserByUserName(userName);
		if (oldUser != null) {
			String oldUserName = oldUser.getUserName();
			if (oldUserName.equals(userName)) {
				if (!oldUser.getUserId().equals(user.getUserId())) {
					return new JsonResponse(ResponseConstant.CODE_FAIL, "用戶名称已存在，请重新输入");
				}
			}
		}
		try {
			//验证姓名不能重复
			User realNameUser = userService.getUserByRealName(realName);
			if (realNameUser != null) {
				if (!realNameUser.getUserId().equals(user.getUserId())) {
					return new JsonResponse(ResponseConstant.CODE_FAIL, "姓名已存在");
				}
			}
			userService.updateUser(user, roleIds, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("UserController updateUser 修改用户失败：" + e.getMessage());
			return new ControllerException("修改用户失败" );
		}
		return "";
	}

	/**
	 * 用户列表
	 */
	@RequestMapping(value = "/list")
	public String listUser(Integer status, String userName,Long departmentId, String departmentName, Integer pageNum, Integer pageSize, HttpServletRequest request, Model model) {
		try {
			PageInfo<UserListVO> pageInfo = userService.listUser(status, userName,departmentId, pageNum, pageSize);
			model.addAttribute("status", status);
			model.addAttribute("userName", userName);
			model.addAttribute("departmentId", departmentId);
			model.addAttribute("departmentName", departmentName);
			model.addAttribute("userList", pageInfo.getList());
			model.addAttribute("pageNum", pageInfo.getPageNum());
			model.addAttribute("pageSize", pageInfo.getPageSize());
			model.addAttribute("total", pageInfo.getTotal());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("UserController listUser 用户列表失败：" + e.getMessage());
		}
		return "user_list";
	}

	/**
	 * 启用禁用用户
	 */
	@ResponseBody
	@RequestMapping(value = "/enableDisableUser", method = RequestMethod.POST)
	public Object enableDisableUser(Long userId, Integer status, HttpServletRequest request) {
		if (userId == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "用户ID不能为空，请联系管理员");
		}
		if (status == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "状态不能为空，请联系管理员");
		}
		try {
			userService.enableDisableUser(userId, status, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("UserController enableDisableUser 启用禁用用户失败：" + e.getMessage());
			return new ControllerException("启用禁用用户失败");
		}
		return "";
	}

	/**
	 * 批量启用用户
	 *
	 * @param ids        用户id(多个英文逗号隔开)
	 * @param status     状态（0启用，1禁用）
	 * @param request    请求
	 * @author linqiang
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/batchAbleDisable", method = RequestMethod.POST)
	public Object batchAbleDisable(String ids,Integer status, HttpServletRequest request) {
		if (StringUtils.isBlank(ids)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "请选择需要启用的用户");
		}
		if (status == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "状态不能为空，请联系管理员");
		}
		try {
			User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
			String ip = HttpUtils.getRemortIP(request);
			userService.batchAbleDisable(ids, status, loginUser, ip);
			if(BusinessConstant.STATUS_ENABLE == status){
				return new JsonResponse(ResponseConstant.CODE_SUCCESS, "批量启用用户成功");
			} else {
				return new JsonResponse(ResponseConstant.CODE_SUCCESS, "批量禁用用户成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("UserController batchAbleDisable 批量启用禁用用户失败：" + e.getMessage());
		}
		if(BusinessConstant.STATUS_ENABLE == status){
			return new JsonResponse(ResponseConstant.CODE_FAIL, "批量启用用户失败");
		} else {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "批量禁用用户失败");
		}
	}

	/**
	 * 重置密码
	 */
	@ResponseBody
	@RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
	public Object resetPassword(Long userId, String password, HttpServletRequest request) {
		if (userId == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "用户ID不能为空，请联系管理员");
		}
		if (StringUtils.isBlank(password)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "密码不能为空");
		}
		try {
			//校验密码的长度和是否包含特殊字符及长度，
			Matcher newMatcher = PASSWORD_PATTERN.matcher(password);
			if (!newMatcher.matches()) {
				return new JsonResponse(ResponseConstant.CODE_FAIL, "密码长度为6-14位，且不能包含特殊字符");
			}
			//校验密码是否与原始密码相同
			User user = userService.getUserById(userId);
			if (user == null) {
				return new JsonResponse(ResponseConstant.CODE_FAIL, "用户不存在,请联系管理员");
			}
			if (DigestUtils.md5Hex(password).equals(user.getPassword())) {
				return new JsonResponse(ResponseConstant.CODE_FAIL, "新输入密码与原始密码相同，请重新输入");
			}
			userService.resetPassword(userId, password, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("UserController resetPassword 重置密码失败：" + e.getMessage());
			return new ControllerException("重置密码失败");
		}
		return "";
	}

}
